import { NextRequest, NextResponse } from 'next/server';
import { templateExportService } from '@/lib/template-export';
import { verifyAuth } from '@/lib/auth-middleware';

export async function POST(request: NextRequest) {
  try {
    const authResult = await verifyAuth();
    
    if (!authResult.success || !authResult.user) {
      return NextResponse.json({
        success: false,
        error: authResult.error
      }, { status: authResult.status || 401 });
    }

    const body = await request.json();
    const { classificationCode, specialty, objectCategory, includeExamples = true, maxRows = 100 } = body;

    if (!classificationCode) {
      return NextResponse.json({
        success: false,
        error: '缺少分类代码参数'
      }, { status: 400 });
    }

    // 生成模板
    const templateBuffer = await templateExportService.generateRoleBasedTemplate({
      classificationCode,
      specialty,
      objectCategory,
      userRole: authResult.user.role_code,
      includeExamples,
      maxRows
    });

    // 设置响应头
    const headers = new Headers();
    headers.set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    headers.set('Content-Disposition', `attachment; filename="template_${classificationCode}_${Date.now()}.xlsx"`);

    return new NextResponse(templateBuffer, {
      status: 200,
      headers
    });

  } catch (error) {
    console.error('导出模板失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '导出模板失败'
    }, { status: 500 });
  }
}